package iamutkarshtiwari.github.io.ananas.editimage.view;

import iamutkarshtiwari.github.io.ananas.editimage.utils.DensityUtil;
import iamutkarshtiwari.github.io.ananas.editimage.utils.LogUtil;
import ohos.agp.components.*;
import ohos.agp.render.Canvas;
import ohos.agp.render.Paint;
import ohos.agp.render.Texture;
import ohos.agp.utils.Color;
import ohos.app.Context;
import ohos.media.image.PixelMap;
import ohos.media.image.common.PixelFormat;
import ohos.media.image.common.Size;

import java.util.ArrayList;
import java.util.List;

public class TextStickerView extends DependentLayout {
    private Image bitmapHolderImageView;
    private PixelMap pixelMap;

    public TextStickerView(Context context) {
        super(context);
        init(null);
    }

    public TextStickerView(Context context, AttrSet attrs) {
        super(context, attrs);
        init(attrs);
    }

    /**
     * 初始化
     *
     * @param attrs 属性
     */
    private void init(AttrSet attrs) {
    }


    /**
     * 获取显示原图的控件
     *
     * @return 返回显示原图的控件
     */
    public Image getBitmapHolderImageView() {
        return bitmapHolderImageView;
    }

    /**
     * 更新原图到控件
     *
     * @param bitmap 原图
     */
    public void updateImageBitmap(PixelMap bitmap) {
        if (bitmapHolderImageView != null) {
            removeComponent(bitmapHolderImageView);
        }

        bitmapHolderImageView = new Image(getContext());
        //Setup image attributes
        DependentLayout.LayoutConfig imageViewParams = new DependentLayout.LayoutConfig(
                ComponentContainer.LayoutConfig.MATCH_PARENT, ComponentContainer.LayoutConfig.MATCH_PARENT);
        imageViewParams.addRule(LayoutConfig.CENTER_IN_PARENT, LayoutConfig.TRUE);
        bitmapHolderImageView.setLayoutConfig(imageViewParams);
        bitmapHolderImageView.setScaleMode(Image.ScaleMode.ZOOM_CENTER);

        bitmapHolderImageView.setPixelMap(bitmap);
        addComponent(bitmapHolderImageView);
    }

    //    int textWidth = 0;
    int singleTextWidth = 133; //单个文字的宽度 和density有关系
    //    int textHigh = 0;
    int singleTextHight = 151;  //单行文字的高度 和density有关系
    int showWidth = 0;
    int showHeight = 0;
    //    int startTextX = 0;
    //    int startTextY = 0;
    int lineMaxText = 0;
    //    int showMaxTextLine = 0;
    //    int textMargin = 0;

    private void getTextInfo(Text text, float scale, int type) {
        float widthImage = bitmapHolderImageView.getPixelMap().getImageInfo().size.width;
        float heightImage = bitmapHolderImageView.getPixelMap().getImageInfo().size.height;
        if (type == 2) {
            showWidth = bitmapHolderImageView.getWidth();
            showHeight = (int) (heightImage * (showWidth / widthImage));
        } else {
            showHeight = bitmapHolderImageView.getHeight();
            showWidth = (int) (widthImage * (showHeight / heightImage));
        }

        if (DensityUtil.getDensityDpi(getContext()) == 530) {
            singleTextWidth = 133;
            singleTextHight = 177;
        } else {
            singleTextWidth = (int) ((133 * DensityUtil.getDensityDpi(getContext())) / 530);
            singleTextHight = (int) ((177 * DensityUtil.getDensityDpi(getContext())) / 530);
        }
        lineMaxText = (showWidth % singleTextWidth == 0) ? (showWidth / singleTextWidth - 1) : showWidth / singleTextWidth;  //不同手机导致的   1080 2400
        if (lineMaxText > 8) {
            lineMaxText = 8;
        }
    }


    private List<Text> list = new ArrayList<>();

    /**
     * 文字的绘制
     *
     * @param bitmap   修改的原图
     * @param string   添加的字符串
     * @param x        绘制文字的右下角的x轴坐标
     * @param y        绘制文字文本的右下角Y轴的坐标
     * @param color    字符的颜色
     * @param textSize 字条大小
     * @param scalx    x轴缩放
     * @param scaly    y轴缩放
     * @param text     TextView
     * @param scale    缩放
     * @param type     缩放类型
     */
    public void drawText(final PixelMap bitmap, String string, float x, float y, Color color, int textSize, float scalx, float scaly, Text text, float scale, int type) {
        getTextInfo(text, scale, type);
        int height = text.getHeight();
        PixelMap.InitializationOptions options = new PixelMap.InitializationOptions();
        options.pixelFormat = PixelFormat.ARGB_8888;
        options.size = new Size(showWidth, showHeight); //canvas的坐标系是按照图片显示的(0,0)开始
        //添加文字的范围是(0,0,showWidth,showHeight)
        options.editable = true;
        pixelMap = PixelMap.create(bitmap, options);  //需要create后才能修改

        Paint paint = new Paint();
        paint.setColor(color);
        paint.setStrokeWidth(90);
        paint.setTextSize(textSize);   //需要同text中设置的字体大小以及位置一样，使用paint保持一致
        LogUtil.loge("gongmengfei paintSize" + paint.getTextSize()); // 133
        Canvas mPaintCanvas = null;
        try {
            mPaintCanvas = new Canvas(new Texture(pixelMap));
            if (height > 177) {  //多行字符
                subLongString(text, string);  //获取所有的text  list的大小，行数
                int middle = 0;
                for (int i = 0; i < list.size(); i++) {
                    int count = list.get(i).getText().length();
                    if (list.size() % 2 != 0) {
                        middle = list.size() / 2;
                        mPaintCanvas.drawText(paint, list.get(i).getText().trim(), (float) ((showWidth - count * singleTextWidth) / 2d + (double) x),
                                (float) (showHeight / 2d + singleTextHight / 2d - (double) paint.descent() + (i - middle) * singleTextHight + (double) y));  // 150  50
                    } else {
                        middle = list.size() / 2;
                        mPaintCanvas.drawText(paint, list.get(i).getText().trim(), (float) ((showWidth - count * singleTextWidth) / 2d + (double) x), (float) (showHeight / 2d + singleTextHight / 2d - (double) paint.descent() + (i - middle) * singleTextHight + 88 + (double) y));
                    }
                }
            } else {
                mPaintCanvas.drawText(paint, string, (float) ((showWidth - text.getWidth()) / 2d + (double) x), (float) (showHeight / 2d + text.getHeight() / 2d - (double) paint.descent() + (double) y));
            }
            mPaintCanvas.scale(scalx, scaly);
        } catch (Exception e) {
            e.printStackTrace();
        }
        if (mPaintCanvas != null) {
            mPaintCanvas.restore();
        }
        invalidate();
    }

    /**
     * 传入的字符进行截取，方便后续分行显示
     *
     * @param text       传入数据的text
     * @param showString 传入的所有字符串
     */
    private void subLongString(Text text, String showString) {
        list.clear();
        int height = text.getHeight();
        //    int size = (height % singleTextHight == 0) ? height / singleTextHight : height / singleTextHight + 1;//(showString.length()%9 == 0)?showString.length()/9:showString.length()+1;
        List<String> result = getStringByNext(showString);//获取所有字符串的长度
        for (int i = 0; i < result.size(); i++) {
            Text text1 = new Text(getContext());
            text1.setText(result.get(i));
            list.add(text1);
        }
    }

    private List<String> getStringByNext(String show) {
        String[] result = show.split("\\r?\\n");
        StringBuilder stringBuilder = new StringBuilder(9);
        List<String> list = new ArrayList<>();
        for (int i = 0; i < result.length; i++) {
            if (result[i].length() <= lineMaxText) {
                list.add(result[i]);
            } else if (result[i].length() > lineMaxText) {
                int count = 0;
                int last = 0;
                int maxSize = (result[i].length()) / (lineMaxText);
                for (int j = 0; j < result[i].length(); j++) {
                    if ((j + 1) % (lineMaxText) == 0) {
                        list.add(result[i].substring(last, j + 1));
                        last = j + 1;
                        count++;
                        continue;
                    }
                    if ((result[i].length()) % (lineMaxText) != 0 && count == maxSize)
                        stringBuilder.append(result[i].toCharArray()[j]);
                }
                if (stringBuilder.length() > 0) {
                    list.add(stringBuilder.toString());
                }
            }
        }

        return list;
    }

    /**
     * 返回 当前的图
     *
     * @return 获取当前的图
     */
    public PixelMap getPixelMap() {
        return pixelMap;
    }

}
